import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/collect/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class AddMeter extends StatefulWidget {
  const AddMeter({super.key});

  @override
  State<StatefulWidget> createState() => _AddMeterState();

}

class _AddMeterState extends State<AddMeter> {
  Map<String, dynamic> _params = {
    "name": "",
    "number": "",
    "model": "",
    "collectId": "",
    "collectName": ""
  };
  List _collectList = [];

  bool checkIsNext () {
    return Utils.isNotEmpty(_params["name"]) && Utils.isNotEmpty(_params["number"]) && Utils.isNotEmpty(_params["model"]) && Utils.isNotEmpty(_params["collectName"]);
  }

  void _addElectricityMeter() async {
    EasyLoading.show();
    await electricityMeterApi.saveElectricityMeter(_params);
    EasyLoading.showToast("添加成功");
    Stacker.pop(true);
  }

  void _getCollectList() async {
    Map<String, dynamic> params = {};
    Map resData = await collectApi.getCollects(params);
    setState(() {
      _collectList = resData["rows"] ?? [];
    });
  }

  void _selectCollect() async {
    if (_collectList.isEmpty) {
      // 如果采集器列表为空，提示用户添加采集器
      final bool? result = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text("提示"),
            content: const Text("暂无采集器，是否前往添加采集器？"),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text("取消"),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: const Text("确定"),
              ),
            ],
          );
        },
      );
      
      if (result == true) {
        // 跳转到添加采集器页面
        final dynamic addResult = await Navigator.of(context).pushNamed(Keys.DEVICE_COLLECT_ADD);
        if (addResult == true) {
          // 如果添加采集器成功，刷新采集器列表
          _getCollectList();
        }
      }
      return;
    }
    
    Map? popped = await showRoundedBottomSheet(
      builder: (context) => BottomSheetSelect(
        items: _collectList,
        compare: (item) => item["number"] == _params["collectId"],
        itemAsString: (item) => item["name"],
      ),
    );
    if (popped != null) {
      setState(() {
        _params["collectId"] = popped["number"];
        _params["collectName"] = popped["name"];
      });
    };
  }

  @override
  void initState() {
    _getCollectList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: const Text("添加智能电表", style: TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: ListView(
        children: [
          MenuBlock(
            borderRadius: const BorderRadius.all(Radius.circular(0)),
            items: [
              MenuBlockItem(
                prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                text: "表号",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入",
                    hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                    isDense: true,
                  ),
                  onChanged: (value) {
                    setState(() {
                      _params["number"] = value;
                    });
                  },
                )
              ),
              MenuBlockItem(
                  prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                  text: "电表名称",
                  showArrow: false,
                  suffix: TextField(
                    textAlign: TextAlign.right,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      hintText: "请输入电表名称",
                      hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                      isDense: true,
                    ),
                    onChanged: (value) {
                      setState(() {
                        _params["name"] = value;
                      });
                    },
                  )
              ),
              // MenuBlockItem(
              //   prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
              //   text: "电表名称",
              //   suffix: groupValue == ""
              //     ? const Text("请选择分组", style: TextStyle(color: ThemeVars.colorTextTer),)
              //     : Text(groupValue),
              //   onTap: () {
              //     showSelectGroup(
              //       context: context,
              //       groupValue: groupValue,
              //       statusBarHeight: MediaQuery.of(context).padding.top,
              //       onChange: (value) {
              //         setState(() {
              //           groupValue = value;
              //         });
              //       },
              //     );
              //   }
              // ),
              MenuBlockItem(
                prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                text: "电表型号",
                showArrow: false,
                suffix: TextField(
                  textAlign: TextAlign.right,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入电表型号",
                    hintStyle: TextStyle(color: ThemeVars.colorTextTer, fontWeight: FontWeight.w400),
                    isDense: true,
                  ),
                  onChanged: (value) {
                    setState(() {
                      _params["model"] = value;
                    });
                  },
                )
              ),
              MenuBlockItem(
                  prefix: const Text("*", style: TextStyle(color: ThemeVars.colorError),),
                  text: "采集器编号",
                  onTap: () {
                    _selectCollect();
                  },
                  suffix: Text(_params["collectName"].isEmpty ? "请选择" : _params["collectName"]),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(left: ThemeVars.paddingPage, right: ThemeVars.paddingPage, top: 60),
            child: CupertinoButton.filled(
              padding: const EdgeInsets.symmetric(vertical: 10),
              disabledColor: ThemeVars.colorDisabled,
              onPressed: checkIsNext() ? () {
                _addElectricityMeter();
              } : null,
              child: const Text("下一步"),
            ),
          ),
        ],
      ),
    );
  }

}